package com.yljk.yljkproject.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.aliyun.aliyunface.api.ZIMCallback;
import com.aliyun.aliyunface.api.ZIMFacade;
import com.aliyun.aliyunface.api.ZIMResponse;
import com.google.gson.Gson;
import com.shicheng.alerts.AlertDialogManager;
import com.shicheng.alerts.callback.AlertDialogCallback;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yljk.servicemanager.constants.ClickApi;
import com.yljk.servicemanager.constants.RouterApi;
import com.yljk.servicemanager.constants.UrlApi;
import com.yljk.servicemanager.interfaceapi.NetWorkCallBack;
import com.yljk.servicemanager.oldbase.ModuleBaseActivity;
import com.yljk.yljkproject.R;
import com.yljk.yljkproject.aliyunface.MyZIMFacade;
import com.yljk.yljkproject.aliyunface.MyZIMFacadeBuilder;
import com.yljk.yljkproject.entity.FaceBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

@Route(path = RouterApi.FaceActivity)
public class FaceActivity extends ModuleBaseActivity implements TextureView.SurfaceTextureListener {

    private ImageView webBack;
    private TextView webviewtitle;
    private Camera mCamera;
    private String title = "";
    private String content = "";
    private static ZimFaceCallBack mZimFaceCallBack;
    @Autowired
    String certifyId;

    private boolean select = false;
    private TextureView textureView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int bondLayout() {
        return R.layout.activity_face;
    }

    @Override
    public void initView() {
        findViewById(R.id.web_back)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        webviewtitle = (TextView) findViewById(R.id.webviewtitle);
        webviewtitle.setText("人脸验证");

        textureView = (TextureView) findViewById(R.id.ttv);
        textureView.setSurfaceTextureListener(this);
        findViewById(R.id.select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (select) {
                    select = false;
                    ((ImageView) findViewById(R.id.select)).setBackgroundResource(R.mipmap.uncheck);
                } else {
                    select = true;
                    ((ImageView) findViewById(R.id.select)).setBackgroundResource(R.mipmap.check);
                }
            }
        });

        ClickUtils.setFastOnClickListener(findViewById(R.id.bookTxt), new View.OnClickListener() {
            @Override
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public void onClick(View v) {
                alertTXT();
            }
        });


        ClickUtils.setFastOnClickListener(findViewById(R.id.start_cv), new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                if (select) {
                    facade();
                    return;
                }
                alertTXT();
            }
        });

    }

    @Override
    public void initData() {
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("documentNo", "faceVerificationProtocol");
        getDocumentTXT(jsonObject);
    }

    @Override
    public void initEvent() {

    }

    @Override
    protected void onStop() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        super.onStop();
    }

    void facade() {

        ClickUtils.sendEvent(ClickApi.App.App_Verification, FaceActivity.this, "人脸识别开始验证点击");
        //                    ZIMFacade zimFacade = ZIMFacadeBuilder.create(reactContext.getCurrentActivity());
        MyZIMFacade zimFacade = MyZIMFacadeBuilder.create(this);
        HashMap<String, String> extParams = new HashMap<>();
//如需自定义活体检测页面的进度条颜色（默认可不设置），请设置此项，如红色 #FF0000。
        extParams.put(ZIMFacade.ZIM_EXT_PARAMS_KEY_OCR_BOTTOM_BUTTON_COLOR, "#3776F9");
// 如需支持活体视频返回，请指定这一项，并在response.videoFilePath中获取视频本地路径。
        extParams.put(ZIMFacade.ZIM_EXT_PARAMS_KEY_USE_VIDEO, ZIMFacade.ZIM_EXT_PARAMS_VAL_USE_VIDEO_TRUE);
        extParams.put(ZIMFacade.ZIM_EXT_PARAMS_KEY_FACE_PROGRESS_COLOR, "#3776F9");

        zimFacade.verify(certifyId, true, extParams, new ZIMCallback() {
            @Override
            public boolean response(ZIMResponse response) {
                try {
                    JSONObject object = new JSONObject();
                    object.put("code", response.code);
                    object.put("deviceToken", response.deviceToken);
                    object.put("reason", response.reason);
                    object.put("msg", response.msg);
                    object.put("videoFilePath", response.videoFilePath);
                    if (mZimFaceCallBack != null) {
                        mZimFaceCallBack.response(object.toString());
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (mZimFaceCallBack != null) {
                        mZimFaceCallBack.error(e);
                        finish();
                    }
                }
                return true;
            }
        });
    }

    void getCheckoutPreserveAgreement(RequestParams jsonObject) {
        HttpUtils.get(UrlApi.checkPreserveAgreement, jsonObject, new HttpCallBack<String>() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onSuccess(String result, int code) {
                if (code != 200 && TextUtils.isEmpty(result)) return;
                try {
                    JSONObject resultJSON = new JSONObject(result);
                    if (resultJSON.getBoolean("data")) {
                        alertTXT();
                    } else {
                        select = true;
                        ((ImageView) findViewById(R.id.select)).setBackgroundResource(R.mipmap.check);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {

            }
        });
    }

    void getDocumentTXT(RequestParams jsonObject) {
        LoadingUtils.getLoadingUtils(this).showLoading();
        HttpUtils.get(UrlApi.getByDocumentNo, jsonObject, new HttpCallBack<FaceBean>() {
            @Override
            public void onSuccess(FaceBean faceBean, int code) {
                if (faceBean.isResult() && faceBean.getData() != null) {
                    title = faceBean.getData().getTitle();
                    content = faceBean.getData().getContent();
                    getCheckoutPreserveAgreement(jsonObject);
                }
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {

            }
        });
    }

    public static void setZimFaceCallBack(ZimFaceCallBack zimFaceCallBack) {
        mZimFaceCallBack = zimFaceCallBack;
    }

    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
        try {
            mCamera = Camera.open(1);
            Camera.Parameters parameters = mCamera.getParameters();

            List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();//获取所有支持的camera尺寸

            Camera.Size optionSize = getOptimalPreviewSize(supportedPreviewSizes, textureView.getHeight(), textureView.getWidth());//获取一个最为适配的camera.size

            parameters.setPreviewSize(optionSize.width, optionSize.height);//把camera.size赋值到parameters

            mCamera.setParameters(parameters);

            mCamera.setDisplayOrientation(90);
            if (mCamera != null) {
                mCamera.setPreviewTexture(surface);
                mCamera.startPreview();
            }
        } catch (Throwable throwable) {

        }

    }

    @Override
    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

    }

    public interface ZimFaceCallBack {
        void response(String msg);

        void error(JSONException e);
    }


    public void user_disAgree() {
        select = false;
        ((ImageView) findViewById(R.id.select)).setBackgroundResource(R.mipmap.uncheck);
        AlertDialogManager.dismiss();
    }

    public void user_agree() {
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("documentNo", "faceVerificationProtocol");
        HttpUtils.get(UrlApi.preserveAgreement, jsonObject, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String result, int code) {
                if (code == 200) {
                    try {
                        JSONObject jsonObject1 = new JSONObject(result);
                        boolean data = jsonObject1.getBoolean("data");
                        if (data) {
                            AlertDialogManager.dismiss();
                            select = true;
                            ((ImageView) findViewById(R.id.select)).setBackgroundResource(R.mipmap.check);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {

            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    void alertTXT() {
        AlertDialogManager.builder()
                .setContext(FaceActivity.this)
                .setType(2)
                .setNegativeButton("不同意")
                .setPositiveButton("同意")
                .setTitle(title)
                .setContent(content)
                .setBottomItemCallback(new AlertDialogCallback() {
                    @Override
                    public void ERROR() {

                    }

                    @Override
                    public void ERROR(String s) {
                        ClickUtils.sendEvent(ClickApi.App.App_FaceAgree, FaceActivity.this, "人脸识别不同意点击");
                        user_disAgree();
                    }

                    @Override
                    public void ERROR(int i, String s) {

                    }

                    @Override
                    public void Success() {

                    }

                    @Override
                    public void Success(String s) {
                        ClickUtils.sendEvent(ClickApi.App.App_FaceAgree, FaceActivity.this, "人脸识别同意点击");
                        user_agree();
                    }

                    @Override
                    public void Success(int i, String s) {

                    }
                })
                .show();
    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;
        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;
        int targetHeight = h;
// Try to find an size match aspect ratio and size
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
// Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }
}